package com.chance.cc.crawler.development.scripts.yicai;

import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.filter.FilterInfo;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.tags.LabelTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AutoVMCommonField.Tag_Field_Topic_Type;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2021/6/29 15:48
 * @Description
 *      第一财经
 **/
public class YiCaiCrawlerScript extends CrawlerCommonScript {

    private static Logger log = LoggerFactory.getLogger(YiCaiCrawlerScript.class);
    private static final String DOMAIN = "yicai";
    private static final String REQUEST_AGAIN_TAG = DOMAIN +"_request_retry";
    private static final String PREFIX = "https://www.yicai.com";

    private static final String NEWS_URL = "http[s]*://www.yicai.com/api/ajax/[a-z]*\\?action=\\S*";
    private static final String ITEM_URL = "http[s]*://www.yicai.com/news/\\d+.html";

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return DOMAIN;
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(NEWS_URL);
        addUrlRegular(ITEM_URL);
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }



    /**
     * 解析链接方法
     *
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();
        String requestUrl = crawlerRequestRecord.getHttpRequest().getUrl();

        if (!httpPage.isDownloadSuccess() || (httpPage.getStatusCode() != 200)) {
            log.error("{} status code : {}", crawlerRequestRecord.getHttpRequest().getUrl(), httpPage.getStatusCode());
            if (httpPage.getStatusCode() != 404) {
                requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
            }
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        if(requestUrl.matches(NEWS_URL)){
            newsUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        if(requestUrl.matches(ITEM_URL)){
            itemUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        return parsedLinks;
    }

    private void newsUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage,List<CrawlerRequestRecord> parsedLinks){
        try{
            httpPage.getJson().toList(JSONObject.class);
        }catch (Exception e){
            requestAgainCrawlerRecord(parsedLinks,crawlerRequestRecord);
            return;
        }
        String requestUrl = httpPage.getRequest().getUrl();
        String nextUrl = getNextUrl(requestUrl, "", "page");
        CrawlerRequestRecord nextRecord = CrawlerRequestRecord.builder()
                .turnPageRequest(crawlerRequestRecord)
                .httpUrl(nextUrl)
                .releaseTime(System.currentTimeMillis())
                .httpHeads(httpPage.getRequest().getHeaders())
                .copyBizTags()
                .copyResultTags()
                .build();
        parsedLinks.add(nextRecord);

        List<JSONObject> jsonObjects = httpPage.getJson().toList(JSONObject.class);
        for (JSONObject jsonObject : jsonObjects) {
            String itemUrl = jsonObject.getString("url");
            String releaseTime = jsonObject.getString("CreateDate");
            if(StringUtils.isBlank(releaseTime) || StringUtils.isBlank(itemUrl)){
                continue;
            }
            itemUrl = PREFIX + itemUrl;
            try {
                long timeToLong = washTimeToLong(releaseTime.replace("T",""));
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .httpUrl(itemUrl)
                        .releaseTime(timeToLong)
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
    }

    private void itemUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage,List<CrawlerRequestRecord> parsedLinks){
        //暂时未有评论、评论
        CrawlerResultTags resultTags = crawlerRequestRecord.tagsCreator().resultTags();
        if(resultTags.hasDataType(CrawlerEnum.CrawlerDataType.comment)){
            resultTags.getCategoryTag().removeLabelTag("comment");
        }

        if(resultTags.hasDataType(CrawlerEnum.CrawlerDataType.interaction)){
            resultTags.getCategoryTag().removeLabelTag("interaction");
        }
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags resultTags = crawlerRecord.tagsCreator().resultTags();

        if (resultTags.hasDataType(CrawlerEnum.CrawlerDataType.article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));
        }
        return crawlerDataList;
    }

    private CrawlerData washArticle(CrawlerRequestRecord requestRecord, HttpPage httpPage) {
        String site = requestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") +1,itemUrl.lastIndexOf("."));

        String title = httpPage.getHtml().xpath("//h1").get();
        String name = httpPage.getHtml().xpath("//p[@class=\"names\"]").get();
        String source = httpPage.getHtml().xpath("//span[@class=\"f-fl\"]").get();
        String author = "";
        if(StringUtils.isNotBlank(name)){
            String[] split = name.split("    ");
            for (String s : split) {
                if(s.matches("作者：\\W+")){
                    author=s.split("：")[1];
                }
            }
        }
        String intro = httpPage.getHtml().xpath("//div[@class=\"intro\"]").get();
        List<String> all = httpPage.getHtml().xpath("//div[@id=\"multi-text\"]//p//text()").all();
        StringBuffer contentBf = new StringBuffer();
        if(StringUtils.isBlank(intro)){
            contentBf.append("");
        }else{
            contentBf.append(intro);
        }
        for (String s : all) {
            if(StringUtils.isBlank(s)){
                continue;
            }

            contentBf.append(s).append(" ");
        }

        List<String> imags = httpPage.getHtml().xpath("//div[@id=\"multi-text\"]//img/@src").all();
        List<String> keywords = httpPage.getHtml().xpath("//div[@class=\"m-keywords\"]/p/a/text()").all();

        CrawlerData crawlerData = CrawlerData.builder()
                .data(requestRecord, httpPage)
                .dataId(StringUtils.joinWith("-", requestRecord.getDomain(), site, CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                .url(itemUrl)
                .releaseTime(requestRecord.getReleaseTime())
                .addContentKV(Field_Title, getContentNoEs(title))
                .addContentKV(Field_Author, author)
                .addContentKV(Field_Source, source)
                .addContentKV(Field_Content, getContentNoEs(contentBf.toString()))
                .addContentKV(Field_Images, imags.toString())
                .build();
        if(keywords != null && keywords.size() > 0){
            crawlerData.tagsCreator().bizTags().addCustomKV(Tag_Field_Topic_Type,keywords);
        }
        return crawlerData;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private void requestAgainCrawlerRecord(List<CrawlerRequestRecord> crawlerRequestRecords, CrawlerRequestRecord crawlerRecord) {
        CrawlerBusinessTags crawlerBusinessTags = crawlerRecord.tagsCreator().bizTags();
        int count = 0;
        if (crawlerBusinessTags.hasKVTag(REQUEST_AGAIN_TAG)) {
            count = (int) crawlerBusinessTags.getCategoryTag().getKVTag(REQUEST_AGAIN_TAG).getVal();
            if (count >= 20) {
                log.error("sina download page the number of retries exceeds the limit" +
                        ",request url {},detail is [{}]", crawlerRecord.getHttpRequest().getUrl(), JSONObject.toJSONString(crawlerRecord));
                return;
            }
        }

        String requestUrl = crawlerRecord.getHttpRequest().getUrl();
        CrawlerRequestRecord crawlerRequestRecord = null;
        LabelTag type = crawlerRecord.tagsCreator().requestTags().getCategoryTag().getLabelTags().get("turn_page_item_request");
        if (type == null) {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        } else {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }

        crawlerRequestRecord.setNeedWashPage(crawlerRecord.isNeedWashPage());
        crawlerRequestRecord.setNeedParsedPage(crawlerRecord.isNeedParsedPage());
        crawlerRequestRecord.getHttpRequest().setHeaders(crawlerRecord.getHttpRequest().getHeaders());
        crawlerRequestRecord.getHttpRequest().setExtras(crawlerRecord.getHttpRequest().getExtras());
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV(REQUEST_AGAIN_TAG, ++count);
        crawlerRequestRecords.add(crawlerRequestRecord);
    }

    private static String washContent(String regx, String input) {
        Pattern compile = Pattern.compile(regx);
        Matcher matcher = compile.matcher(input);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }

    //获取没有转义符号的字符串
    private static String getContentNoEs(String content) {
        if (StringUtils.isBlank(content)) {
            return "";
        }

        int time = 0;
        String result = content;
        while (content.contains("&") && content.contains(";")) {
            result = StringEscapeUtils.unescapeHtml(result);
            if (time >= 5) {
                break;
            }
            time++;
        }
        return result;
    }

    private static long washTimeToLong(String time) throws ParseException {
        if (StringUtils.isBlank(time)) {
            return 0;
        }

        time = time.trim();
        if (time.matches("\\d{2}月\\d{2}日") || time.matches("\\d{2}月\\d{2}日 \\d{2}:\\d{2}")) {
            time = LocalDate.now().getYear() + time;
        }
        return DateUtils.parseDate(time, "yyyy-MM-dd HH:mm:ss", "发表于 yyyy/MM/dd HH:mm", "yyyyMM月dd日",
                "yyyy-MM-dd HH:mm", "yyyyMM月dd日 HH:mm", "日期：yyyy-MM-dd", "yyyy年MM月dd日 HH:mm","yyyy-MM-ddHH:mm:ss").getTime();
    }

    private String getNextUrl(String requestUrl, String keyword, String page) {
        String[] split = requestUrl.split("\\?");
        String nextUrl = split[0] + "?";
        List<NameValuePair> parse = URLEncodedUtils.parse(split[1], Charset.defaultCharset());
        for (NameValuePair nameValuePair : parse) {
            String name = nameValuePair.getName();
            String value = nameValuePair.getValue();
            if (StringUtils.isNotBlank(page) && page.equals(name)) {
                nextUrl = nextUrl + name + "=" + (Integer.parseInt(value) + 1) + "&";
            } else if (StringUtils.isNotBlank(keyword) && keyword.equals(name)) {
                try {
                    nextUrl = nextUrl + name + "=" + URLEncoder.encode(value, "UTF-8") + "&";
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage());
                }
            } else {
                nextUrl = nextUrl + name + "=" + value + "&";
            }
        }
        return nextUrl.substring(0, nextUrl.length() - 1);
    }

    private Map<String, String> getMapFormUrl(String requestUrl) {
        Map<String, String> map = new HashMap<>();
        String[] split = requestUrl.split("\\?");
        List<NameValuePair> parse = URLEncodedUtils.parse(split[1], Charset.defaultCharset());
        for (NameValuePair nameValuePair : parse) {
            String name = nameValuePair.getName();
            String value = nameValuePair.getValue();
            map.put(name, value);
        }
        return map;
    }

    /**
     * 判断是否在时间范围内
     *
     * @param crawlerRequestRecord
     * @return
     */
    private boolean isDateRange(CrawlerRequestRecord crawlerRequestRecord, Long releaseTimeToLong) {
        boolean isRange = false;
        CrawlerEnum.CrawlerRecordFilter filter = crawlerRequestRecord.getFilter();
        if (filter == CrawlerEnum.CrawlerRecordFilter.keyOrDateRange || filter == CrawlerEnum.CrawlerRecordFilter.dateRange) {
            List<FilterInfo> filterInfos = crawlerRequestRecord.getFilterInfos();
            Long startTime = null;
            Long endTime = null;
            for (FilterInfo filterInfo : filterInfos) {
                if (filterInfo.getFilter() == CrawlerEnum.CrawlerRecordFilter.dateRange) {
                    long[] dateAllowRange = filterInfo.getDateAllowRange();
                    int hourFromNow = filterInfo.getHourFromNow();
                    if (dateAllowRange != null) {
                        startTime = dateAllowRange[0];
                        endTime = dateAllowRange[1];
                    } else if (hourFromNow != 0) {
                        endTime = System.currentTimeMillis();
                        startTime = endTime - DateUtils.MILLIS_PER_HOUR * hourFromNow;
                    }
                }
            }
            if (startTime != null && releaseTimeToLong != 0 && startTime <= releaseTimeToLong && releaseTimeToLong <= endTime) {
                isRange = true;
            }
        } else {
            isRange = true;
        }
        return isRange;
    }

    public static void main(String[] args) {
        String s = "https://a.sina.cn/t/author/19656553/";

        String substring = s.substring(s.substring(0, s.length() - 1).lastIndexOf("/") + 1);
        System.out.println(substring);


    }
}
